import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xinxuan/controllers/common_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/authentication_vo.dart';
import 'package:xinxuan/vo/identities_vo.dart';
import 'package:common_utils/common_utils.dart';

class AuthenticationPageController extends GetxController {

  final CommonPageController commonPageController = Get.find();

  /// 认证信息
  var authenticationData = AuthenticationData().obs;
  /// 真实姓名
  var realname = '';
  /// 身份证号码
  var number = ''.obs;
  /// 身份证正面ID
  int frontOfIdCard = 0;
  var frontOfIdCardPath = ''.obs;
  /// 身份证反面ID
  int reverseSideOfIdCard = 0;
  var reverseSideOfIdCardPath = ''.obs;
  
  @override
  void onReady() {
    getUserIdentities();
    super.onReady();
  }

  /// 获取实名认证信息
  getUserIdentities() async {
    if (commonPageController.userData.value.isIdentity == 0) {
      realname = '';
      number.value = '';
      frontOfIdCard = 0;
      frontOfIdCardPath.value = '';
      reverseSideOfIdCard = 0;
      reverseSideOfIdCardPath.value = '';
    } else {
      IdentitiesVo identitiesVo = await HttpUtilService.getUserIdentities();
      realname = identitiesVo.data!.realname!;
      number.value = identitiesVo.data!.number!;
      frontOfIdCard = identitiesVo.data!.images![0].id!;
      frontOfIdCardPath.value = identitiesVo.data!.images![0].image!;
      reverseSideOfIdCard = identitiesVo.data!.images![1].id!;
      reverseSideOfIdCardPath.value = identitiesVo.data!.images![1].image!;
    }
    update();
  }

  /// 用户实名认证
  userAuthentication() async {
    if (TextUtil.isEmpty(realname)) {
      EasyLoading.showToast('请输入姓名');
      return;
    }
    if (!RegexUtil.isIDCard18(number.value)) {
      EasyLoading.showToast('请输入正确的身份证号码');
      return;
    }
    if (frontOfIdCard <= 0) {
      EasyLoading.showToast('请上传身份证正面图片');
      return;
    }
    if (reverseSideOfIdCard <= 0) {
      EasyLoading.showToast('请上传身份证反面图片');
      return;
    }
    
    String imageIds = '$frontOfIdCard,$reverseSideOfIdCard';
    AuthenticationVo authenticationVo = await HttpUtilService.userAuthentication(realname: realname, number: number.value, imageIds: imageIds);
    authenticationData.value = authenticationVo.data!;
    EasyLoading.showToast('认证成功');
    Get.back();
    commonPageController.checkLogin(loading: false);
  }

}